﻿using System;
using UnityEditor;
using UnityEngine;

namespace GameBasic.Editors
{
    public static class EnumDrawerUtil
    {
        /// <summary>
        /// Draw primary-secondary <see cref="Enum"/> popup menus.
        /// </summary>
        /// <typeparam name="C">Primary Type</typeparam>
        /// <param name="position">Region</param>
        /// <param name="cat">Primary Catergory value</param>
        /// <param name="sub">Sub Catergory value</param>
        /// <param name="subs">Sub Catergory Options</param>
        public static void Draw<C>(Rect position, ref Enum32<C> cat, ref int sub, Type[] subs) where C : unmanaged, Enum
        {
            // cat
            position.width *= 0.5f;
            int c = Convert.ToInt32(EditorGUI.EnumPopup(position, cat));
            cat = c;

            // basetype
            if (subs.IsLegalIndex(c) && subs[c] != null)
            {
                position.x += position.width;
                sub = Draw(position, subs[c], sub);
            }
        }

        /// <summary>
        /// Draw primary-secondary <see cref="Enum"/> popup menus. <seealso cref="Draw{C}(Rect, ref Enum32{C}, ref int, Type[])"/>
        /// </summary>
        public static void Draw<C>(Rect position, SerializedProperty cat, SerializedProperty sub, Type[] subs) where C : unmanaged, Enum
        {
            Enum32<C> iCat = cat.intValue;
            int iSub = sub.intValue;
            Draw(position, ref iCat, ref iSub, subs);
            cat.intValue = iCat;
            sub.intValue = iSub;
        }

        public static int Draw(Rect position, Type type, int value)
        {
            // is Flag?
            bool isFlag = false;
            var attributes = type.GetCustomAttributesData();
            for (int i = 0, length = attributes.Count; i < length; i++)
            {
                if (attributes[i].AttributeType == typeof(FlagsAttribute))
                {
                    isFlag = true;
                    break;
                }
            }

            if (isFlag)
                value = Convert.ToInt32(EditorGUI.EnumFlagsField(position, (Enum)Enum.ToObject(type, value)));
            else
                value = Convert.ToInt32(EditorGUI.EnumPopup(position, (Enum)Enum.ToObject(type, value)));

            return value;
        }
    }
}
